﻿using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.FileProviders;
using NLog.Web;
using System.Reflection;
using System.Runtime.Loader;

namespace HHFileViewServer
{
    public static class Middleware
    {
        /// <summary>
        /// 配置文件
        /// </summary>
        /// <param name="builder"></param>
        public static void SetConfig(this WebApplicationBuilder builder)
        {
            ServerOp.ServerConfig = ConfigHelper.GetConfig();
            // 创建默认文件夹
            if (!Directory.Exists(Const.DefaultFolder))
                Directory.CreateDirectory(Const.DefaultFolder);

            // 下载地址
            if (string.IsNullOrEmpty(ServerOp.ServerConfig.DownloadPath) || ServerOp.ServerConfig.DownloadPath == "default")
            {
                ServerOp.ServerConfig.DownloadPath = Const.DefaultFolder;
            }
            else
            {
                // 检测下载路径是否正确（如果地址不存在，取默认）
                if (!Directory.Exists(ServerOp.ServerConfig.DownloadPath))
                {
                    ServerOp.ServerConfig.DownloadPath = Const.DefaultFolder;
                }
            }
            // LibreOffice安装目录(这里不检查地址真实性，放在转换时检查)
            if (string.IsNullOrEmpty(ServerOp.ServerConfig.LibreOffice)
                || ServerOp.ServerConfig.LibreOffice == "default")
            {
                ServerOp.ServerConfig.LibreOffice = Const.DefaultLibreOfficePath;
            }
            // 自动清理服务
            if (ServerOp.ServerConfig.ClearConfig.AutoClear)
            {
                builder.Services.AddHostedService<BackroundService>();
            }
        }

        /// <summary>
        /// 注册系统服务
        /// </summary>
        /// <param name="builder"></param>
        public static void RegisterSystemService(this WebApplicationBuilder builder)
        {
            builder.Logging.ClearProviders();
            builder.Host.UseNLog();
            // Add services to the container.
            builder.Services.AddRazorPages();
            builder.Services.AddHttpClient();
        }

        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="builder"></param>
        public static void RegisterService(this WebApplicationBuilder builder)
        {
            var deps = DependencyContext.Default;
            var libs = deps.CompileLibraries.Where(x =>
                !x.Name.ToLower().StartsWith("microsoft") &&
                !x.Name.ToLower().StartsWith("system") &&
                !x.Name.ToLower().StartsWith("nlog"));
            foreach (var lib in libs)
            {
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));

                var types = assembly.GetTypes().Where(x => x.GetInterfaces().Contains(typeof(IService)));
                if (!types.Any())
                    continue;

                foreach (var item in types)
                {
                    builder.Services.AddScoped(typeof(IService), item);
                }
            }
        }

        /// <summary>
        /// 中间件引用
        /// </summary>
        /// <param name="builder"></param>
        public static void Configure(this WebApplicationBuilder builder)
        {
            var app = builder.Build();
            if (!app.Environment.IsDevelopment())
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.MapRazorPages();
            // 添加MIME（pdfjs）
            var provider = new FileExtensionContentTypeProvider();
            provider.Mappings[".properties"] = "application/octet-stream";
            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = provider
            });

            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), ServerOp.ServerConfig.DownloadPath)),
                RequestPath = new PathString("/file")
            });
            app.Run();
        }
    }
}
